package com.example.seabedmusic.views;


import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.example.seabedmusic.R;
import com.example.seabedmusic.contract.MusicContract;
import com.example.seabedmusic.entity.Playlist;
import com.example.seabedmusic.entity.Song;
import com.example.seabedmusic.presenter.MusicPresenter;
import com.example.seabedmusic.utils.LocalMusicManager;
import com.example.seabedmusic.utils.PlaylistManager;
import com.example.seabedmusic.utils.RecentPlayManager;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class MusicPlayerActivity extends AppCompatActivity implements MusicContract.IMusicView {

    private ImageButton btnBack, btnPlayPause, btnPrevious, btnNext, btnFavorite, btnAddToPlaylist;
    private TextView tvSongName, tvLyrics, tvCurrentTime, tvTotalTime;
    private SeekBar seekBar;

    private MediaPlayer mediaPlayer;
    private Handler handler = new Handler();
    private boolean isPlaying = false;
    private boolean isPrepared = false;

    private List<Song> songList = new ArrayList<>();
    private int currentSongIndex = 0;
    private MusicContract.IMusicPresenter mPresenter;
    private PlaylistManager playlistManager;
    private RecentPlayManager recentPlayManager;
    private ImageButton btnDownload;
    private LocalMusicManager localMusicManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music_player);

        // 初始化Presenter
        mPresenter = new MusicPresenter(this, this);
        // 初始化歌单管理器
        playlistManager = PlaylistManager.getInstance();

        // 初始化最近播放管理器
        recentPlayManager = RecentPlayManager.getInstance(this);
        // 初始化本地音乐管理器
        localMusicManager = LocalMusicManager.getInstance(this);
        initViews();
        setupMediaPlayer();
    }

    private void initViews() {
        btnBack = findViewById(R.id.btnBack);
        btnPlayPause = findViewById(R.id.btnPlayPause);
        btnPrevious = findViewById(R.id.btnPrevious);
        btnNext = findViewById(R.id.btnNext);
        btnFavorite = findViewById(R.id.btnFavorite);
        btnAddToPlaylist = findViewById(R.id.btnAddToPlaylist);
        btnDownload = findViewById(R.id.btnDownload);
        tvSongName = findViewById(R.id.tvSongName);
        tvLyrics = findViewById(R.id.tvLyrics);
        tvCurrentTime = findViewById(R.id.tvCurrentTime);
        tvTotalTime = findViewById(R.id.tvTotalTime);

        seekBar = findViewById(R.id.seekBar);

        // 初始禁用播放按钮
        btnPlayPause.setEnabled(false);

        setListeners();
    }

    /**
     * 设置媒体播放器 - 从Intent获取数据
     */
    private void setupMediaPlayer() {
        try {
            // 从Intent获取传递的数据
            String songTitle = getIntent().getStringExtra("song_title");
            String songArtist = getIntent().getStringExtra("song_artist");
            String songUrl = getIntent().getStringExtra("song_url");
            String songCover = getIntent().getStringExtra("song_cover");
            String songAlbum = getIntent().getStringExtra("song_album");
            String songLyrics = getIntent().getStringExtra("song_lyrics");
            boolean isRandom = getIntent().getBooleanExtra("isRandom", false);
            boolean isFavorite = getIntent().getBooleanExtra("is_favorite", false);


            android.util.Log.d("MusicPlayerActivity", "接收到歌曲数据: " +
                    "title=" + songTitle +
                    ", artist=" + songArtist +
                    ", url=" + songUrl);

            if (songTitle != null && !songTitle.isEmpty()) {
                // 创建Song对象
                Song receivedSong = new Song();
                receivedSong.setTitle(songTitle);
                receivedSong.setArtist(songArtist != null ? songArtist : "未知歌手");
                receivedSong.setUrl(songUrl != null ? songUrl : "");
                receivedSong.setCover(songCover);
                receivedSong.setAlbum(songAlbum != null ? songAlbum : "未知专辑");
                receivedSong.setLyrics(songLyrics);
                receivedSong.setId(String.valueOf(System.currentTimeMillis()));

                if (isFavorite) {
                    receivedSong.setFavorite(true);
                } else {
                    // 检查是否已经在"我喜欢的"中
                    boolean isSongFavorite = playlistManager.isFavorite(receivedSong);
                    receivedSong.setFavorite(isSongFavorite);
                }

                // 将接收到的歌曲添加到播放列表
                songList.clear();
                songList.add(receivedSong);
                currentSongIndex = 0;

                // 更新UI
                updateSongInfo();

                // 准备播放
                prepareMediaPlayer();
            } else {
                android.util.Log.e("MusicPlayerActivity", "未接收到有效的歌曲数据");
                Toast.makeText(this, "未找到歌曲数据", Toast.LENGTH_SHORT).show();
                finish();
            }

        } catch (Exception e) {
            android.util.Log.e("MusicPlayerActivity", "播放器初始化失败", e);
            Toast.makeText(this, "播放器初始化失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            finish();
        }
    }

    /**
     * 准备媒体播放器
     */
    private void prepareMediaPlayer() {
        try {
            // 先释放之前的 MediaPlayer
            releaseMediaPlayer();

            mediaPlayer = new MediaPlayer();
            isPrepared = false;

            Song currentSong = songList.get(currentSongIndex);

            // 记录到最近播放
            recentPlayManager.addToRecent(currentSong);
            android.util.Log.d("MusicPlayerActivity", "歌曲已添加到最近播放: " + currentSong.getTitle());

            // 检查URL是否有效
            if (currentSong.getUrl() != null && !currentSong.getUrl().isEmpty()) {
                mediaPlayer.setDataSource(currentSong.getUrl());
                android.util.Log.d("MusicPlayerActivity", "设置数据源: " + currentSong.getUrl());
            } else {
                Toast.makeText(this, "暂无播放链接", Toast.LENGTH_SHORT).show();
                return;
            }

            // 设置音频流类型
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);

            mediaPlayer.prepareAsync();

            mediaPlayer.setOnPreparedListener(mp -> {
                runOnUiThread(() -> {
                    isPrepared = true;
                    int duration = mp.getDuration();
                    seekBar.setMax(duration);
                    tvTotalTime.setText(formatTime(duration));
                    btnPlayPause.setEnabled(true);
                    hideLoading();

                    android.util.Log.d("HotMusicPlayerActivity", "媒体准备完成，时长: " + duration);

                    // 重置进度条到开始位置
                    seekBar.setProgress(0);
                    tvCurrentTime.setText("0:00");

                    // 自动开始播放
                    togglePlayPause();
                });
            });

            mediaPlayer.setOnCompletionListener(mp -> {
                isPlaying = false;
                isPrepared = false;
                btnPlayPause.setSelected(false);
                android.util.Log.d("MusicPlayerActivity", "播放完成");
                // 播放完成后自动播放下一首
                playNextSong();
            });

            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                isPrepared = false;
                android.util.Log.e("MediaPlayer", "播放错误: what=" + what + ", extra=" + extra);
                Toast.makeText(MusicPlayerActivity.this, "播放错误", Toast.LENGTH_SHORT).show();
                return true;
            });

        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(this, "音频文件加载失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }

    private void togglePlayPause() {
        if (mediaPlayer == null || !isPrepared) {
            android.util.Log.w("MediaPlayer", "MediaPlayer 未准备就绪");
            return;
        }

        try {
            if (isPlaying) {
                mediaPlayer.pause();
                btnPlayPause.setSelected(false);
                handler.removeCallbacks(updateTimeTask);
                android.util.Log.d("MediaPlayer", "暂停播放");
            } else {
                mediaPlayer.start();
                btnPlayPause.setSelected(true);
                updateSeekBar();
                android.util.Log.d("MediaPlayer", "开始播放");
            }
            isPlaying = !isPlaying;
        } catch (IllegalStateException e) {
            android.util.Log.e("MediaPlayer", "播放状态异常: " + e.getMessage());
            Toast.makeText(this, "播放状态异常，正在重新准备", Toast.LENGTH_SHORT).show();
            prepareMediaPlayer();
        }
    }

    private void playPreviousSong() {
        showToast("正在获取随机歌曲...");
        mPresenter.getRandomMusic();
    }

    private void playNextSong() {
        showToast("正在获取随机歌曲...");
        mPresenter.getRandomMusic();
    }

    /**
     * 获取当前歌曲
     */
    private Song getCurrentSong() {
        if (!songList.isEmpty() && currentSongIndex >= 0 && currentSongIndex < songList.size()) {
            return songList.get(currentSongIndex);
        }
        return null;
    }

    private void updateSongInfo() {
        if (!songList.isEmpty()) {
            Song currentSong = songList.get(currentSongIndex);
            tvSongName.setText(currentSong.getTitle());

            // 更新喜欢按钮状态
            btnFavorite.setSelected(currentSong.isFavorite());
            // 更新下载按钮状态
            updateDownloadButtonState();
            // 显示艺术家信息
            if (currentSong.getArtist() != null && !currentSong.getArtist().isEmpty()) {
                tvLyrics.setText(currentSong.getArtist());
            } else {
                tvLyrics.setText("未知歌手");
            }

            // 如果有歌词就显示歌词，否则显示专辑信息
            if (currentSong.getLyrics() != null && !currentSong.getLyrics().isEmpty()) {
                tvLyrics.setText(currentSong.getLyrics());
            } else if (currentSong.getAlbum() != null && !currentSong.getAlbum().isEmpty()) {
                tvLyrics.setText("专辑: " + currentSong.getAlbum());
            } else {
                tvLyrics.setText("暂无信息");
            }

            seekBar.setProgress(0);
            tvCurrentTime.setText("0:00");
            tvTotalTime.setText("0:00");
        }
    }

    /**
     * 切换喜欢状态 - 红色爱心
     */
    private void toggleFavorite() {
        if (songList.isEmpty()) return;

        Song currentSong = getCurrentSong();
        if (currentSong == null) return;

        boolean newState = !currentSong.isFavorite();

        if (newState) {
            // 添加到"我喜欢的"
            boolean success = playlistManager.addToFavorite(currentSong);
            if (success) {
                currentSong.setFavorite(true);
                btnFavorite.setSelected(true);
                Toast.makeText(this, "已添加到我喜欢", Toast.LENGTH_SHORT).show();
                android.util.Log.d("MusicPlayerActivity", "歌曲已添加到我喜欢，当前数量: " + playlistManager.getFavoriteCount());
            } else {
                Toast.makeText(this, "已在我喜欢中", Toast.LENGTH_SHORT).show();
            }
        } else {
            // 从"我喜欢的"移除
            boolean success = playlistManager.removeFromFavorite(currentSong);
            if (success) {
                currentSong.setFavorite(false);
                btnFavorite.setSelected(false);
                Toast.makeText(this, "已从我喜欢移除", Toast.LENGTH_SHORT).show();
                android.util.Log.d("MusicPlayerActivity", "歌曲已从我喜欢移除，当前数量: " + playlistManager.getFavoriteCount());
            }
        }
    }

    private void updateSeekBar() {
        if (isPrepared && isPlaying) {
            handler.post(updateTimeTask);
        }
    }

    private Runnable updateTimeTask = new Runnable() {
        public void run() {
            if (mediaPlayer != null && isPrepared && isPlaying) {
                try {
                    int currentPosition = mediaPlayer.getCurrentPosition();
                    seekBar.setProgress(currentPosition);
                    tvCurrentTime.setText(formatTime(currentPosition));
                } catch (IllegalStateException e) {
                    android.util.Log.e("MediaPlayer", "获取当前位置异常: " + e.getMessage());
                    handler.removeCallbacks(this);
                    return;
                }
            }
            handler.postDelayed(this, 1000);
        }
    };

    private void setListeners() {
        btnBack.setOnClickListener(v -> finish());

        btnPlayPause.setOnClickListener(v -> togglePlayPause());

        btnPrevious.setOnClickListener(v -> playPreviousSong());

        btnNext.setOnClickListener(v -> playNextSong());

        btnFavorite.setOnClickListener(v -> toggleFavorite());

        btnAddToPlaylist.setOnClickListener(v -> showPlaylistSelectionDialog());
        btnDownload.setOnClickListener(v -> downloadCurrentSong());

        seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    tvCurrentTime.setText(formatTime(progress));
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 停止自动更新，避免冲突
                handler.removeCallbacks(updateTimeTask);
            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if (mediaPlayer != null && isPrepared) {
                    try {
                        mediaPlayer.seekTo(seekBar.getProgress());
                        // 拖拽结束后立即更新一次进度
                        if (isPlaying) {
                            handler.post(updateTimeTask);
                        }
                    } catch (IllegalStateException e) {
                        android.util.Log.e("MediaPlayer", "seekTo 状态异常: " + e.getMessage());
                    }
                }
            }
        });
    }
    /**
     * 下载当前歌曲到本地音乐
     */
    private void downloadCurrentSong() {
        if (songList.isEmpty()) {
            showToast("暂无歌曲可下载");
            return;
        }

        Song currentSong = getCurrentSong();
        if (currentSong == null) {
            showToast("无法获取当前歌曲");
            return;
        }

        boolean success = localMusicManager.addSongToLocal(currentSong);
        if (success) {
            showToast("已下载到本地音乐");
            // 更新下载按钮状态
            updateDownloadButtonState();
        } else {
            showToast("歌曲已在本地音乐中");
        }
    }
    /**
     * 更新下载按钮状态
     */
    private void updateDownloadButtonState() {
        if (songList.isEmpty()) return;

        Song currentSong = getCurrentSong();
        if (currentSong != null) {
            boolean isInLocal = localMusicManager.isSongInLocal(currentSong);
            btnDownload.setSelected(isInLocal);
        }
    }


    /**
     * 显示歌单选择对话框
     */
    private void showPlaylistSelectionDialog() {
        if (songList.isEmpty()) {
            showToast("暂无歌曲可添加");
            return;
        }

        Song currentSong = getCurrentSong();
        if (currentSong == null) {
            showToast("无法获取当前歌曲");
            return;
        }

        // 获取所有歌单（排除"我喜欢的"歌单，因为已经有单独的喜欢按钮）
        List<Playlist> allPlaylists = playlistManager.getAllPlaylists();
        List<Playlist> userPlaylists = new ArrayList<>();

        for (Playlist playlist : allPlaylists) {
            // 排除"我喜欢的"歌单
            if (!"我喜欢的".equals(playlist.getName())) {
                userPlaylists.add(playlist);
            }
        }

        if (userPlaylists.isEmpty()) {
            // 如果没有用户创建的歌单，提示创建
            showCreatePlaylistDialog(currentSong);
            return;
        }

        // 创建歌单名称数组
        String[] playlistNames = new String[userPlaylists.size()];
        for (int i = 0; i < userPlaylists.size(); i++) {
            playlistNames[i] = userPlaylists.get(i).getName() + " (" + userPlaylists.get(i).getSongCount() + "首)";
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("添加到歌单");
        builder.setItems(playlistNames, (dialog, which) -> {
            Playlist selectedPlaylist = userPlaylists.get(which);
            addSongToPlaylist(currentSong, selectedPlaylist);
        });

        // 添加"新建歌单"选项
        builder.setNeutralButton("新建歌单", (dialog, which) -> {
            showCreatePlaylistDialog(currentSong);
        });

        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 显示创建新歌单对话框
     */
    private void showCreatePlaylistDialog(Song song) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("新建歌单");

        final EditText input = new EditText(this);
        input.setHint("输入歌单名称");
        input.setSingleLine(true);
        builder.setView(input);

        builder.setPositiveButton("创建", (dialog, which) -> {
            String playlistName = input.getText().toString().trim();
            if (!playlistName.isEmpty()) {
                // 创建新歌单并添加歌曲
                Playlist newPlaylist = playlistManager.createPlaylist(playlistName, "新建歌单");
                if (newPlaylist != null) {
                    addSongToPlaylist(song, newPlaylist);
                    showToast("歌单创建成功，歌曲已添加");
                } else {
                    showToast("歌单创建失败");
                }
            } else {
                showToast("请输入歌单名称");
            }
        });
        builder.setNegativeButton("取消", null);
        builder.show();
    }

    /**
     * 添加歌曲到指定歌单
     */
    private void addSongToPlaylist(Song song, Playlist playlist) {
        boolean success = playlistManager.addSongToPlaylist(playlist.getId(), song);
        if (success) {
            showToast("已添加到歌单: " + playlist.getName());
            android.util.Log.d("MusicPlayerActivity",
                    "歌曲已添加到歌单: " + playlist.getName() +
                            ", 当前数量: " + playlist.getSongCount());

            // 发送广播通知歌单页面刷新
            sendPlaylistUpdateBroadcast();
        } else {
            showToast("歌曲已在歌单中");
        }
    }

    /**
     * 发送歌单更新广播
     */
    private void sendPlaylistUpdateBroadcast() {
        // 使用 LocalBroadcastManager
        LocalBroadcastManager.getInstance(this)
                .sendBroadcast(new Intent("PLAYLIST_UPDATED"));
        android.util.Log.d("MusicPlayerActivity", "发送歌单更新广播");
    }

    /**
     * 释放 MediaPlayer 资源
     */
    private void releaseMediaPlayer() {
        if (mediaPlayer != null) {
            try {
                handler.removeCallbacks(updateTimeTask);
                mediaPlayer.stop();
                mediaPlayer.release();
            } catch (IllegalStateException e) {
                android.util.Log.e("MediaPlayer", "释放 MediaPlayer 异常: " + e.getMessage());
            } finally {
                mediaPlayer = null;
                isPrepared = false;
                isPlaying = false;
            }
        }
    }

    private String formatTime(int milliseconds) {
        long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) -
                TimeUnit.MINUTES.toSeconds(minutes);
        return String.format("%d:%02d", minutes, seconds);
    }

    /**
     * 显示Toast消息
     */
    public void showToast(String message) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
    }

    // =============== MusicContract.IMusicView 接口实现 ===============

    @Override
    public void showSongs(List<Song> songs) {
        if (songs != null && !songs.isEmpty()) {
            // 接收到新歌曲，更新播放列表
            songList.clear();
            songList.addAll(songs);
            currentSongIndex = 0;

            // 记录到最近播放
            Song currentSong = getCurrentSong();
            if (currentSong != null) {
                recentPlayManager.addToRecent(currentSong);
            }

            // 更新UI并准备播放
            updateSongInfo();
            prepareMediaPlayer();

            showToast("切换到新歌曲: " + getCurrentSong().getTitle());
        } else {
            showToast("未获取到歌曲数据");
        }
    }

    @Override
    public void showRecent(List<Song> songs) {
        // 播放页面不需要显示最近播放
    }

    @Override
    public void showLoading() {
        btnPrevious.setEnabled(false);
        btnNext.setEnabled(false);
    }

    @Override
    public void hideLoading() {
        btnPrevious.setEnabled(true);
        btnNext.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        releaseMediaPlayer();
        handler.removeCallbacks(updateTimeTask);
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (isPlaying && mediaPlayer != null && isPrepared) {
            try {
                mediaPlayer.pause();
                isPlaying = false;
                btnPlayPause.setSelected(false);
                handler.removeCallbacks(updateTimeTask);
            } catch (IllegalStateException e) {
                android.util.Log.e("MediaPlayer", "暂停时异常: " + e.getMessage());
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mediaPlayer != null && isPrepared && !isPlaying) {
            updateSeekBar();
        }
    }
}